package com.jlh.cookbook.service;

import com.alibaba.fastjson.JSON;
import com.jlh.cookbook.dao.CookDao;
import com.jlh.cookbook.entity.Cook;
import com.jlh.cookbook.entity.DataResp;
import com.jlh.cookbook.utils.HttpClientUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * com.jlh.cookbook.service
 * Created by ASUS on 2017/3/4.
 * 14:15
 */
public class JuheService {
    private String url="http://apis.juhe.cn/cook/index";
    private String key="fa4c63b356b8fe060c64029a397737a5";
    private String rn="30";

    public DataResp doParse(String resp) {
        return JSON.parseObject(resp, DataResp.class);
    }

    public void insertCook() {
        List<String> pids= Arrays.asList("104","117");
        CookDao cookDao = new CookDao();
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        for (String pid :pids) {
            Integer pn=0;
            Integer total=-1;
            Map<String,String> params = new HashMap<>();
            params.put("cid",pid);
            params.put("key",key);
            params.put("rn",rn);
            params.put("pn",pn.toString());
            while (true) {
                //获取数据
                String data = httpClientUtils.get(url,params);
                //解析数据
                DataResp dataResp = doParse(data);
                if (dataResp.getResultcode().equals("200") && dataResp.getError_code().equals(0)) {
                    //入库
                    List<Cook> cooks = dataResp.getResult().getData();
                    for (Cook cook : cooks) {
                        cookDao.insert(cook);
                    }
                    total=Integer.valueOf(dataResp.getResult().getTotalNum());
                    pn+=Integer.valueOf(rn);
                    params.put("pn",pn.toString());
                    if (pn>=total)
                        break;
                } else {
                    System.out.println(dataResp.getError_code() + ":" + dataResp.getReason());
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        JuheService juheService = new JuheService();
        juheService.insertCook();

    }
}
